/**
 * 数组数据根据某个字段分组
 * @param arr 
 * @param generateKey 可以是一个字符串也可以是一个函数
 */

export function groupBy(arr: any, generateKey: any){
  if(typeof generateKey === 'string') {
    const propName = generateKey
    generateKey = (item: any) => item[propName]
  }
  const result:any = {}
  for(const item of arr){
    const key = generateKey(item)
    if(!result[key]){
      result[key] = []
    }
    result[key].push(item)
  }
  return result
}

/**
 * 参数归一化处理函数
 * @param formatter 
 * @returns 
 */
function _formatNormalize(formatter: any) {
  if(typeof formatter === 'function') {
    return formatter
  }
  if(typeof formatter !== 'string') {
    throw new TypeError('formatter must be a string')
  }
  if(formatter === 'data') {
    formatter = 'yyyy-MM-dd'
  }
  else if(formatter === 'datatime'){
    formatter = 'yyyy-MM-dd HH:mm:ss'
  }
  const formarrerFunc = (dateInfo: any) => {
    const {yyyy, MM, dd, HH, mm, ss, ms} = dateInfo
    return formatter.replaceAll('yyyy', yyyy)
    .replaceAll('MM', MM)
    .replaceAll('dd', dd)
    .replaceAll('HH', HH)
    .replaceAll('mm', mm)
    .replaceAll('ss', ss)
    .replaceAll('ms', ms)
  }
  return formarrerFunc
}
/**
 * 
 * @param date
 * @param formatter 
 * @param isPad 
 */
export function formate(date: any, formatter: any, isPad = false){
  formatter = _formatNormalize(formatter)
  const dateInfo: any = {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    date: date.getDate(),
    hour: date.getHours(),
    minute: date.getMinutes(),
    second: date.getSeconds(),
    miniSecond: date.getMilliseconds()
  };
  dateInfo.yyyy = dateInfo.year.toString()
  dateInfo.MM = dateInfo.month.toString()
  dateInfo.dd = dateInfo.date.toString()
  dateInfo.HH = dateInfo.hour.toString()
  dateInfo.mm = dateInfo.minute.toString()
  dateInfo.ss = dateInfo.second.toString()
  dateInfo.ms = dateInfo.miniSecond.toString()
  function _pad(prop: string, len: number) {
    dateInfo[prop] = dateInfo[prop].padStart(len, '0')
  }
  if(isPad) {
    _pad('yyyy', 4)
    _pad('MM', 2)
    _pad('dd', 2)
    _pad('HH', 2)
    _pad('mm', 2)
    _pad('ss', 2)
    _pad('ms', 2)
  }
  const result = formatter(dateInfo)
  return result
}

/**
 *并发执行任务
 * @param tasks 
 * @param parllelCount 
 */
export function paralleTask(tasks: any[], parllelCount = 2){
  return new Promise<void>(resolve=> {
    if(tasks.length ===0){
      resolve()
      return
    }
    let nextIndex = 0
    let finishCount = 0
    function _run() {
      const task = tasks[nextIndex]
      nextIndex++
      task().then(()=> {
        finishCount++
        if(nextIndex<tasks.length){
          _run()
        }
        else if(finishCount === tasks.length){
          resolve()
        }
      })
    }
    for(let i = 0; i < parllelCount && i < tasks.length; i++) {
      _run()
    }
  })
}